package parser3;

import org.antlr.runtime.*;
import org.antlr.runtime.tree.CommonTree;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * @author brianegge
 */
public class Parser3 {

    protected Token down = new CommonToken(Token.DOWN, "<DOWN>");
    protected Token up = new CommonToken(Token.UP, "<UP>");

    public ArrayList<Token> parse(InputStream is) throws IOException, RecognitionException {
        ANTLRInputStream input = new ANTLRInputStream(is);
        JavaLexer lexer = new JavaLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JavaParser parser = new JavaParser(tokens);
        JavaParser.compilationUnit_return unit = parser.compilationUnit();
        CommonTree tree = (CommonTree) unit.getTree();
        ArrayList<Token> tokenList = new ArrayList<Token>();
        getTokenList(tokenList, tree);
        return tokenList;
    }

    private void getTokenList(ArrayList<Token> list, CommonTree tree) {
        if (!tree.isNil()) {
            list.add(tree.getToken());
        }
        if (tree.getChildCount() > 0) {
            list.add(down);
            for (int i = 0; i < tree.getChildCount(); i++) {
                getTokenList(list, (CommonTree) tree.getChild(i));
            }
            list.add(up);
        }
    }
}
